package com.newdjk.newdoctor.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ajguan.library.EasyRefreshLayout;
import com.ajguan.library.LoadModel;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.newdjk.newdoctor.BasActivity;
import com.newdjk.newdoctor.MyApplication;
import com.newdjk.newdoctor.R;
import com.newdjk.newdoctor.adapter.ActivityListAdapter;
import com.newdjk.newdoctor.adapter.SystemListAdapter;
import com.newdjk.newdoctor.net.BaseComPleteObserver;
import com.newdjk.newdoctor.net.NetServices;
import com.newdjk.newdoctor.utils.Contants;
import com.newdjk.newdoctor.utils.Event;
import com.newdjk.newdoctor.utils.RxBus;
import com.newdjk.okhttp.entity.ActivityListEntity;
import com.newdjk.okhttp.entity.BaseEntity;
import com.newdjk.okhttp.entity.SystemListEntity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 重置密码
 */
public class MessageActivity extends BasActivity {


    private static final String TAG = "MessageActivity";
    @BindView(R.id.recyleview)
    RecyclerView recyleview;
    @BindView(R.id.easylayout)
    EasyRefreshLayout easylayout;
    @BindView(R.id.iv_no)
    ImageView ivNo;
    @BindView(R.id.mNodataContainer)
    RelativeLayout mNodataContainer;
    private int type;
    private int pageindex = 1;
    private ArrayList<ActivityListEntity.ReturnDataBean> mOrderList = new ArrayList<>();
    private ActivityListAdapter mOrderListAdapter;
    private Observable<Boolean> activityObservable;
    @Override
    protected String setTitle() {
        return "活动消息";
    }

    @Override
    protected int initViewResId() {
        return R.layout.activity_order;

    }


    @Override
    protected void initListener() {

        easylayout.addEasyEvent(new EasyRefreshLayout.EasyEvent() {
            @Override
            public void onLoadMore() {
                GetOrgAppActivityMessagePage();
            }

            @Override
            public void onRefreshing() {
                pageindex = 1;
                mOrderList.clear();
                easylayout.setLoadMoreModel(LoadModel.COMMON_MODEL);
                GetOrgAppActivityMessagePage();
            }
        });

        mOrderListAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                if (mOrderList.get(position).getIsRead() == 1) {
                    toMessageDetail(position);
                } else {
                    UpdateOrgAppActivityMessageRead(position);
                }

            }
        });

        activityObservable = RxBus.get().register(Event.jpush_activity_list);

        activityObservable.observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                Log.d(TAG, "OrderListActivity更新活动消息列表");
                if (aBoolean) {
                    pageindex = 1;
                    mOrderList.clear();
                    GetOrgAppActivityMessagePage();
                }

            }
        });
    }

    private void UpdateOrgAppActivityMessageRead(int position) {
        if (MyApplication.isLogin) {
            if (MyApplication.LoginEntity==null){
                return;
            }
            NetServices.Factory.getService().UpdateOrgAppActivityMessageRead(
                    MyApplication.LoginEntity.getUser().getDoctorId() + "",
                    1,
                    mOrderList.get(position).getRelationId()+""
            ).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseComPleteObserver<Boolean>(this, true) {
                        @Override
                        protected void onSuccees(BaseEntity<Boolean> t) throws Exception {
                            String url=mOrderList.get(position).getLinkUrl();
                            if (!TextUtils.isEmpty(url)){
                                if (url.startsWith("http")) {
                                    Intent intent = new Intent(MessageActivity.this, WebViewActivity.class);
                                    intent.putExtra("url", url);
                                    intent.putExtra(Contants.TYPE, 31);
                                    startActivity(intent);
                                } else {
                                    Intent intent = new Intent(MessageActivity.this, WebViewActivity.class);
                                    intent.putExtra("innerLink", url);
                                    intent.putExtra(Contants.TYPE, 21);
                                    startActivity(intent);
                                }
                            }


                            mOrderList.get(position).setIsRead(1);
                            mOrderListAdapter.notifyItemChanged(position);
                            RxBus.get().post(Event.jpush_activity_list, false);
                        }

                        @Override
                        protected void onFailure(Throwable e, String erroressage, boolean isNetWorkError) throws Exception {
                            super.onFailure(e, erroressage, isNetWorkError);
                            easylayout.loadMoreFail();


                        }
                    });
        }

    }

    private void toMessageDetail(int position) {

        String url=mOrderList.get(position).getLinkUrl();

        if (url.startsWith("http")) {
            Intent intent = new Intent(this, WebViewActivity.class);
            intent.putExtra("url", url);
            intent.putExtra(Contants.TYPE, 31);
            startActivity(intent);
        } else {
            Intent intent = new Intent(this, WebViewActivity.class);
            intent.putExtra("innerLink", url);
            intent.putExtra(Contants.TYPE, 21);
            startActivity(intent);
        }
    }

    @Override
    protected void initData() {
        GetOrgAppActivityMessagePage();
    }
    private void GetOrgAppActivityMessagePage() {
        if (MyApplication.isLogin) {
            NetServices.Factory.getService().GetOrgAppActivityMessagePage(
                    MyApplication.LoginEntity.getUser().getDoctorId() + "",
                    pageindex,
                    10
            ).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseComPleteObserver<ActivityListEntity>(this, true) {
                        @Override
                        protected void onSuccees(BaseEntity<ActivityListEntity> t) throws Exception {
                            Log.d(TAG, t.getData().getReturnData() + "");
                            if (pageindex != 1) {
                                easylayout.loadMoreComplete();
                            } else {
                                easylayout.refreshComplete();
                            }

                            List<ActivityListEntity.ReturnDataBean> returnlist = t.getData().getReturnData();
                            if (returnlist != null) {
                                if (returnlist.size() >= 10) {  //还有数据
                                    pageindex++;
                                    mOrderList.addAll(returnlist);
                                    mOrderListAdapter.setNewInstance(mOrderList);
                                    mOrderListAdapter.notifyDataSetChanged();
                                } else if (returnlist.size() >= 0 && returnlist.size() < 10) { //加载完成
                                    mOrderList.addAll(returnlist);
                                    mOrderListAdapter.setNewInstance(mOrderList);
                                    easylayout.setLoadMoreModel(LoadModel.NONE);
                                    mOrderListAdapter.notifyDataSetChanged();
                                }
                                //  reFreshNameLetter(returnlist);

                            } else {
                                easylayout.setLoadMoreModel(LoadModel.NONE);
                            }
                            if (mOrderList.size() <= 0) {
                                Log.i("MessageFragment", "lenError");
                                // mEasylayout.setVisibility(View.GONE);
                                recyleview.setVisibility(View.GONE);
                                mNodataContainer.setVisibility(View.VISIBLE);
                            } else {
                                //  mEasylayout.setVisibility(View.VISIBLE);
                                recyleview.setVisibility(View.VISIBLE);
                                mNodataContainer.setVisibility(View.GONE);
                            }

                        }

                        @Override
                        protected void onFailure(Throwable e, String erroressage, boolean isNetWorkError) throws Exception {
                            super.onFailure(e, erroressage, isNetWorkError);
                            easylayout.loadMoreFail();
                            if (mOrderList.size() <= 0) {
                                Log.i("MessageFragment", "lenError");
                                // mEasylayout.setVisibility(View.GONE);
                                recyleview.setVisibility(View.GONE);
                                mNodataContainer.setVisibility(View.VISIBLE);
                            } else {
                                //  mEasylayout.setVisibility(View.VISIBLE);
                                recyleview.setVisibility(View.VISIBLE);
                                mNodataContainer.setVisibility(View.GONE);
                            }

                        }
                    });
        }
    }

    @Override
    protected void initView() {
        type = getIntent().getIntExtra(Contants.TYPE, 0);

        mOrderListAdapter = new ActivityListAdapter(mOrderList);
        recyleview.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyleview.setAdapter(mOrderListAdapter);
    }

    @Override
    public boolean IsShowBackIcon() {
        return true;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
